package com.swsc.solarverse.service.forward.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.swsc.solarverse.common.util.ObjectMapper;
import com.swsc.solarverse.dao.entity.forward.ForwardStringDataDO;
import com.swsc.solarverse.dao.mapper.forward.ForwardStringDataMapper;
import com.swsc.solarverse.service.forward.IForwardStringDataService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author AutoGenerator
 * @since 2022-08-26
 */
@Service
public class ForwardStringDataServiceImpl extends ServiceImpl<ForwardStringDataMapper, ForwardStringDataDO> implements IForwardStringDataService {

    @Override
    public void saveOrUpdateStringData(List<ForwardStringDataDO> dataDos) {
        if (CollectionUtils.isNotEmpty(dataDos)) {
            for (ForwardStringDataDO dataDo : dataDos) {
                ForwardStringDataDO rawDataDo = baseMapper.selectOne(Wrappers.lambdaQuery(ForwardStringDataDO.class)
                        .eq(ForwardStringDataDO::getTenantNo, dataDo.getTenantNo())
                        .eq(ForwardStringDataDO::getOrganNo, dataDo.getOrganNo())
                        .eq(ForwardStringDataDO::getDevicePid, dataDo.getDevicePid())
                        .eq(ForwardStringDataDO::getDeviceId, dataDo.getDeviceId())
                        .orderByDesc(ForwardStringDataDO::getDataTime)
                        .last("LIMIT 1")
                );
                if (null == rawDataDo) {
                    baseMapper.insert(dataDo);
                } else {
                    Long id = rawDataDo.getId();
                    ObjectMapper.map(dataDo, rawDataDo);
                    rawDataDo.setId(id);
                    baseMapper.updateById(rawDataDo);
                }
            }
        }
    }

    @Override
    public void updateDos(List<ForwardStringDataDO> dataDos) {
        if (CollectionUtils.isNotEmpty(dataDos)) {
            for (ForwardStringDataDO dataDo : dataDos) {
                baseMapper.update(dataDo, Wrappers.lambdaUpdate(ForwardStringDataDO.class)
                        .eq(ForwardStringDataDO::getTenantNo, dataDo.getTenantNo())
                        .eq(ForwardStringDataDO::getOrganNo, dataDo.getOrganNo())
                        .eq(ForwardStringDataDO::getDevicePid, dataDo.getDevicePid())
                        .eq(ForwardStringDataDO::getDeviceId, dataDo.getDeviceId())
                );
            }
        }
    }

    @Override
    public void insertOrUpdateBatch(List<ForwardStringDataDO> list) {
        if (CollectionUtils.isNotEmpty(list)) {
            baseMapper.insertOrUpdateBatch(list);
        }
    }
}
